package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 监听课程信息
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class ListenLearningLesson {

    private final ILearningLessonService learningLessonService;
    /**
     * 监听订单退款成功，删除用户相关课程表
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.refund.queue",durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLessonRefund(OrderBasicDTO dto){
        if (dto==null){
            //不做处理 直接返回
            log.error("接收到的MQ消息有误，订单数据为空");
            return;
        }
       learningLessonService.deleteLessonByMq(dto);
    }

    /**
     * 监听订单支付或课程报名信息
     * @param order 订单信息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue",durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE ,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO order){
        //1. 健壮性处理
        if (order==null||order.getUserId()==null){
            //不做处理 直接返回
            log.error("接收到的MQ消息有误，订单数据为空");
            return;
        }
        //2. 添加课程
        log.debug("监听到用户{}的订单{}，需要将课程{}添加到课表中",order.getUserId(),order.getOrderId(),order.getCourseIds());
        learningLessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }
}
